﻿using lingopen.Foxconn.BLE.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace lingopen.Foxconn.BLE.Com
{
    public class SerialPortHelper
    {

        SerialPort _serialPort = new SerialPort();

        public bool IsOpen { get { return _serialPort.IsOpen; } }

        public static string[] SerialPortNames
        {
            get
            {
                string[] serialports = SerialPort.GetPortNames();
                Array.Sort(serialports, new Comparison<string>(
                  delegate (string x, string y)
                  {
                      if (x.Length > 3 && y.Length > 3)
                      {
                          string index1 = x.Substring(3);
                          string index2 = y.Substring(3);
                          try
                          {
                              int n1 = Convert.ToInt32(index1);
                              int n2 = Convert.ToInt32(index2);
                              return n1 - n2;
                          }
                          catch
                          {
                          }
                      }
                      return 0;
                  }));
                return serialports;
            }
        }

        public event SerialDataReceivedEventHandler DataReceived;

        public SerialPortHelper(RichTextBox rtxt)
        {
            _log = new Com.RichTextBoxLog(rtxt);
            _serialPort.DataReceived += _serialPort_DataReceived;
        }

        private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            DataReceived?.Invoke(sender, e);
        }

        Com.RichTextBoxLog _log = null;
        
        public bool Open(string PortName, int BaudRate)
        {
            try
            {
                _serialPort.PortName = PortName;
                _serialPort.StopBits = StopBits.One;
                _serialPort.Parity = Parity.None;
                _serialPort.DataBits = 8;
                _serialPort.BaudRate = BaudRate;
                _serialPort.Open();
            }
            catch (Exception ex)
            {
                _log.LogError(ex + "");
                //输入日志
                return false;
            }

            return true;
        }

        /// <summary>
        /// 打开串口,波特率默认9600
        /// </summary>
        /// <param name="PortName"></param>
        /// <returns></returns>
        public bool Open(string PortName)
        {
            try
            {
                _serialPort.PortName = PortName;
                _serialPort.StopBits = StopBits.One;
                _serialPort.Parity = Parity.None;
                _serialPort.DataBits = 8;
                _serialPort.BaudRate = 9600;
                _serialPort.Open();
            }
            catch (System.UnauthorizedAccessException ex)
            {
                _log.LogError(ex.Message);
                //输入日志
                return false;
            }
            catch (Exception ex)
            {
                _log.LogError(ex + "");
                //输入日志
                return false;
            }
            return true;
        }


        public void Close()
        {
            _serialPort.Close();
        }

        public void WriteLine(string text)
        {
            if (_serialPort.IsOpen)
            {
                //_sendByteOfCount += text.Length;
                _serialPort.WriteLine(text);
            }
        }

        public void Write(byte[] buffer)
        {
            if (_serialPort.IsOpen)
            {
                _serialPort.Write(buffer, 0, buffer.Length);
                //_sendByteOfCount += buffer.Length;
            }
        }

        public void WriteLine16(string text)
        {
            if (_serialPort.IsOpen)
            {
                //我们不管规则了。如果写错了一些，我们允许的，只用正则得到有效的十六进制数
                MatchCollection mc = Regex.Matches(text, @"(?i)[\da-f]{2}");
                List<byte> buf = new List<byte>();//填充到这个临时列表中
                //依次添加到列表中
                foreach (Match m in mc)
                {
                    //buf.Add(byte.Parse(m.Value));
                    buf.Add(byte.Parse(m.Value, System.Globalization.NumberStyles.HexNumber));
                }
                //转换列表为数组后发送
                _serialPort.Write(buf.ToArray(), 0, buf.Count);
                //记录发送的字节数
                //_sendByteOfCount += buf.Count;

                buf = null;
                mc = null;

            }

        }


    }
}
